package client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * netty 用户端
 */
public class NettyClient {

    private static ChannelFuture cf = null;

    public static void main(String[] args) throws InterruptedException {
        //
        new Thread(new Runnable() {
            public void run() {
                clientConnect("127.0.0.1", 8080);
            }
        }).start();

        Thread.sleep(1000);

        // 发送消息测试
        for (int i = 0; i < 10; i++) {
             // 防止消息合并
             Thread.sleep(10);
            // 发送消息
            cf.channel().writeAndFlush(Unpooled.wrappedBuffer(("hello" + i).getBytes())) ;
        }
    }


    /**
     * 客户端连接
     */
    public static void clientConnect(String ip, int port) {
        try {
            // 创建负责接收客户端连接
            NioEventLoopGroup pGroup = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();
            //创建通道
            b.group(pGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) {
                    sc.pipeline().addLast(new StringDecoder());
                    sc.pipeline().addLast(new ClientHandler());
                }
            });
            // 连接
            cf = b.connect(ip, port).sync();
            System.out.println(cf.channel().id() + " 客户端已经启动....");

            // 阻塞当前线程，channel 断开连接时在执行
            cf.channel().closeFuture().sync();
            // 优雅地关闭 EventLoopGroup (Netty中的线程池)
            pGroup.shutdownGracefully();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

